package questions;

import org.junit.jupiter.api.Test;

import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

/**
 * 有两种用法
 * 1.主线程await，子线程countDown，这种场景是用于子线程执行完主线程才能继续
 *
 * 2.主线程countDown 子线程await，是用于子线程要做准备且需要主线程同时唤醒去执行场景
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(7);
        for (int i = 0; i < 7; i++) {
            final int temp = i + 1;
            new Thread(() -> {
                System.out.println("同学" + temp + "走了");
                countDownLatch.countDown();
            }, "" + i).start();
        }
        countDownLatch.await();
        System.out.println("班长关了门");
    }

    /***
     * 这种场景和cyclicbarrier 很像  基本可替换
     * @throws InterruptedException
     */
    @Test
    public void test2() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        IntStream.range(0, 7).forEachOrdered(i -> {
            final int temp = i + 1;
            new Thread(() -> {
                System.out.println("同学" + temp + "来了");
                try {
                    countDownLatch.await();
                    System.out.println(temp+"同学动手");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "同学" + i).start();
        });
        Thread.sleep(3000);
        System.out.println("9点时间到，开始考试");
        countDownLatch.countDown();



    }
}
